package cn.hzu580.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;

import com.opensymphony.xwork2.ActionContext;

import cn.hzu580.bean.CodeDaemon;
import cn.hzu580.bean.LoginedUserPool;
import cn.hzu580.bean.MsgDaemon;
import cn.hzu580.constant.Hzu580Config;
import cn.hzu580.dao.BaseDAO;
import cn.hzu580.entity.User;
import cn.hzu580.service.UserService;
import cn.hzu580.util.FileUtil;
import cn.hzu580.util.MD5Util;
import cn.hzu580.util.VerifyCodeUtil;
import cn.hzu580.vo.UserVO;

@Service("user")
public class UserServiceImpl implements UserService {

	@Resource(name="DAO")
	private BaseDAO baseDAO;
	
	@Resource
	private MsgDaemon daemon;
	
	@Resource
	private LoginedUserPool loginedUserPool;
	
	@Resource
	private CodeDaemon codeDaemon;
	
	@Override
	public String register(UserVO vo) {
		//检查是否已经调用了短信验证码
		Map<String, Object> session = ActionContext.getContext().getSession();
		String msgCode = (String) session.get("msgCode");
		if(msgCode == null || "".equals(msgCode)){
			ServletActionContext.getResponse().setStatus(417);
			return "failed_no_code";
		}
		//检查短信验证码正确性
		if(!msgCode.equals(vo.getCode())){
			ServletActionContext.getResponse().setStatus(417);
			return "failed_code_wrong";
		}
		HashMap<String, Object> parameters = new HashMap<String,Object>();
		parameters.put("uid", vo.getUid());
		parameters.put("tel", session.get("tel"));
		if(!baseDAO.exeQuery("from User where uid=:uid", parameters).isEmpty()){
			ServletActionContext.getResponse().setStatus(417);
			return "failed_uid_exist";
		}
		if(!baseDAO.exeQuery("from User where tel=:tel", parameters).isEmpty()){
			ServletActionContext.getResponse().setStatus(417);
			return "failed_tel_exist";
		}
		
		//赋值
		User user = new User();
		user.setTel((String) ServletActionContext.getRequest().getSession().getAttribute("tel"));
		if(vo.getUid() == null || "".equals(vo.getUid())){
			user.setUid(user.getTel());
		}else{
			user.setUid(vo.getUid());
		}
		user.setSex(vo.isSex());
		user.setName(vo.getName());
		user.setScore(Hzu580Config.INIT_SCORE);
		user.setPermission("000");
		//MD5加密
		user.setPassword(MD5Util.MD5(vo.getPassword()));
		baseDAO.insert(user);
		if(vo.getHead()!= null){
			FileUtil.saveFile(vo.getHead(), "/head",vo.getUid()+".jpg");
		}
		//清除短信验证码
		session.put("msgCode",null);
		return "succeed";
	}

	@Override
	public User login(UserVO vo) {
		HashMap<String, Object> parameters = new HashMap<String,Object>();
		parameters.put("uid", vo.getUid());
		parameters.put("tel", vo.getTel());
		//MD5加密
		parameters.put("password", MD5Util.MD5(vo.getPassword()));
		List<User> list =  (List<User>) baseDAO.exeQuery("from User where (uid=:uid or tel=:tel) and password=:password", parameters);
		if(list.isEmpty()){
			return null;
		}
		//注销
		logout();
		//登录
		User user = list.get(0);
		ActionContext.getContext().getSession().put("uid", user.getUid());
		loginedUserPool.login();
		return user;
	}


	@Override
	public User get(UserVO vo) {
		if(vo.getTel() != null && !vo.getTel().equals("")){
			Map parameters = new HashMap<>();
			parameters.put("tel", vo.getTel());
			return (User) baseDAO.exeQuery("from User where tel=:tel", parameters).get(0);
		}
		return (User) baseDAO.get(User.class, vo.getUid());
	}

	@Override
	public List<User> getRank(UserVO vo) {
		List<User> list =  (List<User>) baseDAO.exeQuery("from User order by score desc", null,0,vo.getTop());
		return list;
	}

	@Override
	public void approve(UserVO vo) {
		Map session = ActionContext.getContext().getSession();
		FileUtil.saveFile(vo.getPaper(), "/WEB-INF/paper",session.get("uid")+".jpg");
	}

	@Override
	public String sign() {
		Map session = ActionContext.getContext().getSession();
		User user = (User) baseDAO.get(User.class, (Serializable) session.get("uid"));
		if(user.isHas_sign()){
			return "0";
		}
		user.setHas_sign(true);
		user.setScore(user.getScore()+Hzu580Config.SIGN_SCORE);
		user.setContinuity_sign(user.getContinuity_sign()+1);
		baseDAO.update(user);
		return user.getContinuity_sign()+"";
	}

	@Override
	public String modifyTel(UserVO vo) {
		//检查是否已经调用了短信验证码
		Map<String, Object> session = ActionContext.getContext().getSession();
		String msgCode = (String) session.get("msgCode");
		if(msgCode == null || "".equals(msgCode)){
			ServletActionContext.getResponse().setStatus(417);
			return "failed_no_code";
		}
		//检查短信验证码正确性
		if(!msgCode.equals(vo.getCode())){
			ServletActionContext.getResponse().setStatus(417);
			return "failed_code_wrong";
		}
		HashMap<String, Object> parameters = new HashMap<String,Object>();
		parameters.put("tel", session.get("tel"));
		List<User> list =  (List<User>) baseDAO.exeQuery("from User where tel=:tel", parameters);
		if(!list.isEmpty()){
			ServletActionContext.getResponse().setStatus(417);
			return "failed_exist";
		}
		User user = (User) baseDAO.get(User.class, (Serializable) session.get("uid"));
		baseDAO.update(user);
		//清除短信验证码
		session.put("msgCode",null);
		//强制登出
		logout();
		return "succeed";
	}

	@Override
	public String modifyPassword(UserVO vo) {
		//检查是否已经调用了短信验证码
		Map<String, Object> session = ActionContext.getContext().getSession();
		String msgCode = (String) session.get("ownerMsgCode");
		if(msgCode == null || "".equals(msgCode)){
			ServletActionContext.getResponse().setStatus(417);
			return "failed_no_code";
		}
		//检查短信验证码正确性
		if(!msgCode.equals(vo.getCode())){
			ServletActionContext.getResponse().setStatus(417);
			return "failed_code_wrong";
		}
		User user = (User) baseDAO.get(User.class, (Serializable) session.get("uid"));
		//MD5加密
		user.setPassword(MD5Util.MD5(vo.getPassword()));
		baseDAO.update(user);
		//清除短信验证码
		session.put("ownerMsgCode",null);
		return "succeed";
	}
	

	@Override
	public String ownerValidate(UserVO vo) {
		Map session = ActionContext.getContext().getSession();
		User user = (User) baseDAO.get(User.class, (Serializable) session.get("uid"));
//		System.out.println(user);
//		//检查是否已经调用了图形验证码
//		String picCode = (String) session.get("picCode");
//		if(picCode == null || "".equals(picCode)){
//			ServletActionContext.getResponse().setStatus(417);
//			return "failed_code_wrong";
//		}
//		//检查图形验证码正确性
//		if(!picCode.equals(vo.getCode().toUpperCase())){
//			ServletActionContext.getResponse().setStatus(417);
//			return "failed_code_wrong";
//		}
		//尝试发送短信验证码
		if(!daemon.trySendMsg(ServletActionContext.getRequest().getSession().getId(),"ownerMsgCode",user.getTel())){
			ServletActionContext.getResponse().setStatus(417);
			return "failed_frequent";
		}
//		//清除图形验证码
//		session.put("picCode",null);
		return "succeed";
	}


	@Override
	public void modifyName(UserVO vo) {
		Map session = ActionContext.getContext().getSession();
		User user = (User) baseDAO.get(User.class, (Serializable) session.get("uid"));
		user.setName(vo.getName());
		baseDAO.update(user);
	}

	@Override
	public void modifyHead(UserVO vo) {
		Map session = ActionContext.getContext().getSession();
		FileUtil.saveFile(vo.getHead(), "/head",session.get("uid")+".jpg");
	}

	@Override
	public void logout() {
		ActionContext.getContext().getSession().put("uid", null);
		loginedUserPool.logout();
	}

	@Override
	public String validateMsg(UserVO vo) {
		Map<String, Object> session = ActionContext.getContext().getSession();
//		//检查是否已经调用了图形验证码
//		String picCode = (String) session.get("picCode");
//		if(picCode == null || "".equals(picCode)){
//			ServletActionContext.getResponse().setStatus(417);
//			return "failed_code_wrong";
//		}
//		//检查图形验证码正确性
//		if(!picCode.equals(vo.getCode().toUpperCase())){
//			ServletActionContext.getResponse().setStatus(417);
//			return "failed_code_wrong";
//		}
		//尝试发送短信验证码
		if(!daemon.trySendMsg(ServletActionContext.getRequest().getSession().getId(),"msgCode",vo.getTel())){
			ServletActionContext.getResponse().setStatus(417);
			return "failed_frequent";
		}
//		//清除图形验证码
//		session.put("picCode",null);
		//保存手机号到会话中
		session.put("tel", vo.getTel());
		return "succeed";
		
	}

	@Override
	public byte[] validatePic() {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
	 	Map session = ActionContext.getContext().getSession();
		try {
			String picCode = VerifyCodeUtil.outputVerifyImage(200, 80, os, 4);
			//把图形验证码放入session中
			session.put("picCode", picCode);
			codeDaemon.time("picCode");
			return os.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	
	public BaseDAO getBaseDAO() {
		return baseDAO;
	}

	public void setBaseDAO(BaseDAO baseDAO) {
		this.baseDAO = baseDAO;
	}

	public MsgDaemon getDaemon() {
		return daemon;
	}

	public void setDaemon(MsgDaemon daemon) {
		this.daemon = daemon;
	}

	public LoginedUserPool getLoginedUserPool() {
		return loginedUserPool;
	}

	public void setLoginedUserPool(LoginedUserPool loginedUserPool) {
		this.loginedUserPool = loginedUserPool;
	}

	public CodeDaemon getCodeDaemon() {
		return codeDaemon;
	}

	public void setCodeDaemon(CodeDaemon codeDaemon) {
		this.codeDaemon = codeDaemon;
	}

	

	

}
